require 'date';
class Task < ActiveRecord::Base
  set_table_name 'task'
  set_primary_key 'task_id'

  belongs_to :project,
             :class_name  => 'Project',
	     :foreign_key => 'project_fk';

  has_many :comments,
           :class_name  => 'Comment',
	   :foreign_key => 'task_fk';

  belongs_to :status,
             :class_name  => 'StatusTask',
	     :foreign_key => 'status_fk';

  belongs_to :user,
             :class_name => 'User',
	     :foreign_key => 'owner';

  belongs_to :iteration,
             :class_name => 'Iteration',
	     :foreign_key => 'iteration_fk';

  validates_presence_of :status_fk, :priority, :subject, :description, :project_fk;	    

  def self.unowned_tasks(limit = 10)
      return find(:all,
                  :conditions => ["owner is null and status_fk in (1,2)"] ,
		  :order      => "created desc",
		  :limit      => limit);
  end

  def validate 
      if (time_worked.to_s !~ /^\d+$/) 
          errors.add('time_worked','has an invalid format. Should contain only numbers');
      end
      if (estimated_time.to_s !~ /^\d+$/) 
          errors.add('estimated_time','has an invalid format. Should contain only numbers');
      end

  end


  # get task
  # returns the task based on task id
  
  def self.get_task(task_id)
      return nil unless task_id; # sane verification
      return find(:first,
                  :conditions => ["task_id = ?", task_id]);
  end

  # get iteration_name
  # returns the iteration name if exists

  def get_iteration_name
      return iteration.name if iteration_fk;
      return nil;
  end


  # start_session
  # start a session for a task

  def start_session
      session = Session.new( :start      => DateTime.now,
                             :end        => nil,
			     :task_fk    => task_id);
      session.save() if session;			     
  end


  # stop_current_session
  # stop current session
  
  def stop_current_session
      current_session = Session.find(:first,
                                     :conditions => ["task_fk = ?", task_id, "end = ?", nil]);
      current_session.end if current_session;				     
  end

end
